package edu.hebtu.controller;

import edu.hebtu.mapper.impl.CarMapper;
import edu.hebtu.mapper.impl.RepairMapper;
import edu.hebtu.mapper.impl.UserMapper;
import edu.hebtu.pojo.Car;
import edu.hebtu.pojo.Repair;
import edu.hebtu.pojo.User;
import edu.hebtu.util.CarIDCheck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Comparator;
import java.util.List;
import java.util.regex.Pattern;

@Controller
public class CarController {

    private final CarMapper carMapper;
    private final UserMapper userMapper;
    private final RepairMapper repairMapper;

    @Autowired
    public CarController(CarMapper carMapper, UserMapper userMapper, RepairMapper repairMapper) {
        this.carMapper = carMapper;
        this.userMapper = userMapper;
        this.repairMapper = repairMapper;
    }

    @RequestMapping("/car_info")
    public String select(Model model) {
        List<Car> cars = carMapper.findById(null);
        for (Car car : cars) {
            List<User> userList = userMapper.findById(car.getCustodian());
            if (userList.size() == 1) car.setCustodian(userList.get(0).getName() + "(" + userList.get(0).getUserId() + ")");
            if (car.getState().trim().equals("appear")) car.setState("正常");
            if (car.getState().trim().equals("repair")) car.setState("修理中");
        }
        model.addAttribute("cars", cars);
        return "tables/table-car";
    }

    private void init_Model(Model model){
        List<User> users = userMapper.findById(null);
        List<Car> cars = carMapper.findById(null);
        users.removeIf(aValue -> aValue.getUserType() == 0);
        users.sort(Comparator.comparing(User::getName).reversed());
        model.addAttribute("users", users);
        model.addAttribute("id", Integer.parseInt(cars.get(cars.size() - 1).getId()) + 1);
    }

    @RequestMapping("/car_add")
    public String car_add(Model model) {
        init_Model(model);
        model.addAttribute("parent", "C1");
        return "add/add-car";
    }

    @RequestMapping("/addCar")
    public String addCar(Car car, Model model) {

        init_Model(model);

        List<Car> cars = carMapper.findById(null);
        boolean flag = false;
        if (car.getLicense() == null || car.getLicense().trim().equals("")) {
            model.addAttribute("msg", "请输入车牌号！！！");
            flag = true;
        } else if (!CarIDCheck.check(car.getLicense())) {
            model.addAttribute("msg", "车牌号格式有误，请重新输入！！！");
            flag = true;
        } else {
            for (Car car1 : cars) {
                if (car.getLicense().trim().equals(car1.getLicense().trim())) {
                    model.addAttribute("msg", "车牌号已存在！！！");
                    flag = true;
                }
            }
        }
        if (car.getId() == null || car.getId().trim().equals("")) {
            model.addAttribute("msg", "请输入车辆编号！！！");
            flag = true;
        } else if(!Pattern.matches("^[1-9]|[1-9]{2}|[1-9]0|[1-9]{3}|[1-9]{2}0|[1-9]00$", car.getId().trim())) {
            model.addAttribute("msg", "车辆编号最长为三位，请重新输入！！！");
            flag = true;
        }

        if (flag) {
            model.addAttribute("license", car.getLicense());
            model.addAttribute("id", car.getId());
            model.addAttribute("parent", car.getParent());
            model.addAttribute("custodian", car.getCustodian());
            return "add/add-car";
        }

        for (Car car1 : cars) {
            if (car1.getId().equals(car.getId())) {
                model.addAttribute("license", car.getLicense());
                model.addAttribute("id", "");
                model.addAttribute("parent", car.getParent());
                model.addAttribute("custodian", car.getCustodian());
                model.addAttribute("msg", car.getId() + "号车已存在，添加失败！！！");
                return "add/add-car";
            }
        }

        if (carMapper.add(car) == 1) {
            model.addAttribute("parent", "C1");
            model.addAttribute("id", Integer.parseInt(car.getId()) + 1);
            model.addAttribute("msg", car.getId() + "号车添加成功。");
        } else {
            model.addAttribute("msg", "添加失败！！！");
        }
        return "add/add-car";
    }

    @RequestMapping("/car_edit/{carId}")
    public String car_edit(@PathVariable("carId")String carId, Model model) {
        Car car = carMapper.findById(carId).get(0);
        List<User> users = userMapper.findById(null);
        users.removeIf(aValue -> aValue.getUserType() == 0);
        users.sort(Comparator.comparing(User::getName).reversed());
        model.addAttribute("users", users);
        model.addAttribute("car", car);
        return "edit/edit-car";
    }

    @RequestMapping("/editCar")
    public String editCar(Car car, Model model) {

        init_Model(model);

        List<Car> cars = carMapper.findById(null);
        cars.removeIf(aValue -> aValue.getCarId().trim().equals(car.getCarId()));
        boolean flag = false;
        if (car.getLicense() == null || car.getLicense().trim().equals("")) {
            model.addAttribute("msg", "请输入车牌号！！！");
            flag = true;
        } else if (!CarIDCheck.check(car.getLicense())) {
            model.addAttribute("msg", "车牌号格式有误，请重新输入！！！");
            flag = true;
        } else {
            for (Car car1 : cars) {
                if (car.getLicense().trim().equals(car1.getLicense().trim())) {
                    model.addAttribute("msg", "车牌号已存在！！！");
                    flag = true;
                }
            }
        }
        if (car.getId() == null || car.getId().trim().equals("")) {
            model.addAttribute("msg", "请输入车辆编号！！！");
            flag = true;
        } else if(!Pattern.matches("^[1-9]|[1-9]{2}|[1-9]0|[1-9]{3}|[1-9]{2}0|[1-9]00$", car.getId().trim())) {
            model.addAttribute("msg", "车辆编号最长为三位，请重新输入！！！");
            flag = true;
        }

        if (flag) {
            model.addAttribute("license", car.getLicense());
            model.addAttribute("id",car.getId());
            model.addAttribute("parent", car.getParent());
            model.addAttribute("custodian", car.getCustodian());
            return "edit/edit-car";
        }

        if ("ok".equals(car.getState())) {
            List<Repair> repairs = repairMapper.findById(null);
            repairs.removeIf(aValue -> !aValue.getCarId().equals(car.getCarId()));
            repairMapper.delete(repairs.get(0));
            car.setState("appear");
        }

        if (carMapper.update(car) == 1) {
            return "redirect:/car_info";
        } else {
            return "edit/edit-car";
        }
    }

    @RequestMapping("/car_delete/{carId}")
    public String car_delete(@PathVariable("carId")String carId, Model model) {
        Car car = carMapper.findById(carId).get(0);
        List<User> users = userMapper.findById(null);
        users.removeIf(aValue -> aValue.getUserType() == 0);
        users.sort(Comparator.comparing(User::getName).reversed());
        model.addAttribute("users", users);
        model.addAttribute("car", car);
        return "delete/delete-car";
    }

    @RequestMapping("/deleteCar")
    public String deleteCar(Car car) {
        carMapper.delete(car);
        return "redirect:/car_info";
    }

}
